#!/bin/sh

# Installs the system into a zipped CD-ROM ISO image file

IMAGEFLOPPYLOG=${M_DIR_TMP}/image-floppy.log
MKISOFSLOG=${M_DIR_TMP}/mkisofs.log
DISTCOMMENT=${M_DIR_TMP}/distcomment
ZIPLOG=${M_DIR_TMP}/zip.log

echo ""
echo "Making Ailes CD-ROM IMAGE file"

# Are we doing a release version?  If the argument is "-r" then we use
# the release number in the destination directory name.  Otherwise, we
# assume an interim package and use the date instead
if [ "$1" == "-r" ] ; then
	# What is the current release version?
	RELEASE=`./release.sh`
	echo " - doing RELEASE version $RELEASE"
	RELFLAG=-r
else
	# What is the date?
	RELEASE=`date +%Y-%m-%d`
	echo " - doing INTERIM version $RELEASE (use -r flag for RELEASES)"
fi
echo ""

BUILDDIR="$M_DIR_BUILD"
ISOBOOT=-isoboot
NAME=ailes-$RELEASE
FLOPPYZIP="$NAME""$ISOBOOT"-img.zip
FLOPPYIMAGE="$NAME""$ISOBOOT".img
ISOIMAGE=$NAME.iso
ZIPFILE=$NAME-iso.zip

TMPDIR="$M_DIR_TMP/iso$$.tmp"
rm -Rf "$TMPDIR"
mkdir -p "$TMPDIR"

echo -n "Making/copying boot floppy image... "
${M_DIR_UTILS}/image-floppy.sh $RELFLAG $ISOBOOT >& "$IMAGEFLOPPYLOG"
if [ $? -ne 0 ] ; then
	echo ""
	echo -n "Not able to create floppy image $FLOPPYZIP.  "
	echo "See $IMAGEFLOPPYLOG.  Terminating."
	echo ""
	exit 1
fi

rm -f "$IMAGEFLOPPYLOG"
#unzip "$FLOPPYZIP" >& /dev/null
rm -f "$FLOPPYZIP"
mv "$FLOPPYIMAGE" "$TMPDIR"
echo Done

# Copy all of the files from the build directory
echo -n "Copying build files... "
(cd $BUILDDIR ; tar cf - * ) | (cd $TMPDIR; tar xf - )
echo Done

echo -n "Copying doc files... "
(cd $M_DIR_ROOT ; tar cf - docs ) | (cd $TMPDIR; tar xf - )
find $TMPDIR/docs -name .svn -exec rm -Rf '{}' \; >& /dev/null
echo Done

echo -n "Creating ISO image... "
rm -f "$ISOIMAGE"
mkisofs -U -D -floppy-boot -b $FLOPPYIMAGE -c boot.catalog -hide $FLOPPYIMAGE -hide boot.catalog -V "Ailes $RELEASE" -iso-level 3 -L -o $ISOIMAGE $TMPDIR >& $MKISOFSLOG
if [ $? -ne 0 ] ; then
	echo ""
	echo -n "Not able to create ISO image $ISOIMAGE.  "
	echo "See $MKISOFSLOG.  Terminating."
	echo ""
	exit 1
fi
rm -f "$MKISOFSLOG"
echo Done

echo -n "Archiving... "
echo "Ailes $RELEASE CD-ROM Release" > "$DISTCOMMENT"
echo "Copyright (C) 1998-2007 J. Andrew McLaughlin" >> "$DISTCOMMENT"
echo "Copyright (C) 2009 Vadim Ushakov" >> "$DISTCOMMENT"
rm -f "$ZIPFILE"
zip -9 -z -r "$ZIPFILE" "$ISOIMAGE" < "$DISTCOMMENT" >& "$ZIPLOG"
if [ $? -ne 0 ] ; then
	echo ""
	echo -n "Not able to create zip file $ZIPFILE.  "
	echo "See $ZIPLOG.  Terminating."
	echo ""
	exit 1
fi
rm -f "$DISTCOMMENT" "$ZIPLOG"
echo Done

rm -f "$FLOPPYIMAGE"
#rm -f $ISOIMAGE
rm -Rf $TMPDIR

echo ""
echo "File is: $ZIPFILE"
echo ""

exit 0
